Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate COALESCE as ISNULL #34171

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft

Translate COALESCE as ISNULL #34171

wants to merge 3 commits into from

Conversation

ranma42
Copy link
Contributor

@ranma42 ranma42 commented Jul 5, 2024

COALESCEis a syntactic shortcut for the CASE expression. As such, the input values are evaluated multiple times.

ISNULL does not have this shortcoming.

Fixes #32519.

@ranma42 ranma42 marked this pull request as ready for review July 5, 2024 21:34
@ranma42
Copy link
Contributor Author

ranma42 commented Jul 6, 2024

At least a test for the type propagation is needed

`COALESCE`is a syntactic shortcut for the CASE expression. As such, the input
values are evaluated multiple times.

`ISNULL` does not have this shortcoming.

Fixes dotnet#32519.
@ranma42 ranma42 marked this pull request as draft July 6, 2024 09:51
@ranma42
Copy link
Contributor Author

ranma42 commented Jul 6, 2024

It looks like the type mapping computed in Coalesce does not match the actual expression type :(
At least the test was helpful in identifying this issue 😅
This problem could be related to #14719 or #15586

@raymens
Copy link

raymens commented Sep 4, 2024

Another application for this is that COALESCE cannot be used for Indexed Views in SQL Server, however ISNULL is supported in case of aggregations.

This makes it difficult/impossible to make EF Core generated queries use the indexed views as I suppose the query processor thinks they're different.

For example:

CREATE VIEW [dbo].[vAggregation]
   WITH SCHEMABINDING
   AS
      SELECT a, SUM(ISNULL(b, 0.0)) AS bSum, COUNT_BIG(*) AS Count 
      FROM dbo.c
      GROUP BY a
GO

CREATE UNIQUE CLUSTERED INDEX IDX_vAggregation
   ON vAggregation(a)
GO

SELECT SUM(b) FROM c -- SLOW: not using the indexed view
SELECT SUM(COALESCE(b, 0)) FROM c -- SLOW: not using the indexed view
SELECT SUM(ISNULL(b, 0)) FROM c -- FAST: uses the indexed view

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

SQL Server: consider switching from COALESCE to ISNULL
2 participants